package indi.zn.commons.math;

import java.util.ArrayList;
import java.util.List;


/**
 * 组合  C(n,m)
 * @author zn
 * 
 */
public class Combination<T> {

	private Integer m;
	private List<T> content;

	public Integer getSize() {
		return m;
	}

	public List<T> getContent() {
		return content;
	}

	public void setContent(List<T> content) {
		this.content = content;
	}

	public Combination(List<T> content) {

		this.content = content;
		this.m = content.size();

	}

	public List<ArrayList<T>> combination(Integer n) {

		List<ArrayList<T>> res = new ArrayList<ArrayList<T>>();

		ArrayList<T> arr = new ArrayList<T>();

		for (int i = 0; i < n; i++) {

			arr.add(content.get(i));

		}

		Integer e = m - n + 1;
		Integer l = 0;

		for (int i = 1; i <= e; i++) {

			arr.set(l, content.get(i - 1));

			if (n > 1) {
				combi(i, n, l + 1, arr, res);
			} else {

				res.add((ArrayList<T>) arr.clone());

			}

		}

		return res;

	}

	@SuppressWarnings("unchecked")
	private void combi(Integer s, Integer e, Integer l, ArrayList<T> arr, List<ArrayList<T>> res) {

		for (int i = 0; i < m - s; i++) {

			arr.set(l, content.get(i + s));

			if (l < e - 1) {

				combi(s + i + 1, e, l + 1, arr, res);

			} else {

				res.add((ArrayList<T>) arr.clone());

			}
		}

	}


}
